package cn.com.csg.smartenergy.modules.biz.energy.service;

import cn.com.csg.smartenergy.common.Constant;
import cn.com.csg.smartenergy.modules.biz.energy.mapper.EnergyIotProductServiceMapper;
import cn.com.csg.smartenergy.modules.biz.energy.mapper.EnergyIotDeviceMapper;
import cn.com.csg.smartenergy.modules.biz.energy.mapper.EnergyIotProductServicePropMapper;
import cn.com.csg.smartenergy.modules.biz.entity.IotDeviceEntity;
import cn.com.csg.smartenergy.modules.biz.entity.IotProductEntity;
import cn.com.csg.smartenergy.modules.biz.entity.IotProductServiceEntity;
import cn.com.csg.smartenergy.modules.biz.entity.IotProductServicePropEntity;
import cn.com.csg.smartenergy.modules.biz.task.core.CronTaskRegistrar;
import cn.com.csg.smartenergy.modules.biz.task.core.ScheduledTask;
import cn.com.csg.smartenergy.mqtt.DeviceMqttOnlineClient;
import cn.com.csg.smartenergy.util.OperResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EnergyIotDeviceService extends ServiceImpl<EnergyIotDeviceMapper, IotDeviceEntity> implements IService<IotDeviceEntity> {

    private String onlineTopic = "notify/event/gwTerminal/status";
    @Autowired
    private DeviceMqttOnlineClient client;
    @Autowired
    CronTaskRegistrar cronTaskRegistrar;
    @Autowired
    EnergyIotDeviceService energyIotService;
    @Autowired
    private EnergyIotProductService energyIotProductService;
    @Autowired
    private EnergyIotProductServiceMapper iotProductServiceMapper;
    @Autowired
    private EnergyIotProductServicePropMapper iotProductServicePropMapper;
    /**
     * 根据厂商ID、终端类型、终端型号、终端序列号，获取设备信息。
     *
     * @param device 设备
     * @return 设备信息
     */
    public List getaAllDeviceInfo(IotDeviceEntity device) {
        if(device == null) {device = new IotDeviceEntity();};
        List<IotDeviceEntity> deviceInfo = this.baseMapper.getDeviceInfo(device);
        return deviceInfo;
    }

    /**
     * 根据厂商ID、终端类型、终端型号、终端序列号，获取设备信息。获取定时任务状体
     *
     * @param device 设备
     * @return 设备信息
     */

    public List getAllDeviceInfoAndJobStatus(IotDeviceEntity device) {
        if(device == null) {device = new IotDeviceEntity();};
//        energyIotService.getBaseMapper().selectList(null).forEach(System.out::println);
        System.out.println("==============================================================");
        List<IotDeviceEntity> deviceInfo = this.baseMapper.getDeviceInfo(device);
        Map<String, ScheduledTask> allTasks = cronTaskRegistrar.getAllTasks();
        if(CollectionUtils.isNotEmpty(deviceInfo)&&CollectionUtils.isNotEmpty(allTasks)){
            String beanName = "sendTask";
            String methodName1 = "onLine";
            String methodName2 = "sendMessage";
            deviceInfo.forEach(item -> {
                String manufacturerId = item.getManufacturerId();
                String manufacturerName = item.getManufacturerName();
                String deviceType = item.getDeviceType();
                String model = item.getModel();
                String nodeId = item.getNodeId();
                String protocolType = item.getProtocolType();
                String jobId1 = beanName + Constant.UNDER_LINE
                        + methodName1 + Constant.UNDER_LINE
                        + manufacturerId + Constant.UNDER_LINE
                        + nodeId + Constant.UNDER_LINE
                        + protocolType;
                String jobId2 = beanName+Constant.UNDER_LINE
                        + methodName2+Constant.UNDER_LINE
                        + manufacturerId + Constant.UNDER_LINE
                        + nodeId+Constant.UNDER_LINE
                        + protocolType;
                if(allTasks.containsKey(jobId1)){
                    item.setOnlineStatus(1);
                }else{
                    item.setOnlineStatus(0);
                }
                if(allTasks.containsKey(jobId2)) {
                    item.setSendStatus(1);
                }else{
                    item.setSendStatus(0);
                }
            });
        }
        return deviceInfo;
    }

    /**
     * 得到产品_服务list
     * @param productId
     * @return
     */
    public OperResult getIotProductService(Long productId) {
        // 获取产品详情
        Map params = new HashMap();
        params.put("industry", Constant.INDUSTRY);
        params.put("del_flag", Constant.UN_LOGIC_DEL);
        params.put("id", productId);
        List<IotProductEntity> iotProductList = energyIotProductService.getBaseMapper().queryProductList(params);
        if (iotProductList.size() != 1) {
            return OperResult.error(Constant.QUERY_NO_DATA);
        }
        IotProductEntity iotProduct = iotProductList.get(0);
        IotProductServiceEntity iotProductServiceEntity = new IotProductServiceEntity();
        iotProductServiceEntity.setProductId(productId);
        List<IotProductServiceEntity> iotProductServiceList = iotProductServiceMapper.selectList(new QueryWrapper<IotProductServiceEntity>().setEntity(iotProductServiceEntity));
        for (IotProductServiceEntity service : iotProductServiceList) {
            System.out.println(service.getId());
        }
        return OperResult.ok().put("data",iotProductServiceList);
    }

    /**
     * 得到serviceProp list ==>json
     * @param serviceId
     * @return
     */
    public OperResult getServicePropList(Long serviceId) {
        IotProductServicePropEntity iotProductServicePropEntity = new IotProductServicePropEntity();
        iotProductServicePropEntity.setServiceId(serviceId);
        List<IotProductServicePropEntity> iotProductServicePropList = iotProductServicePropMapper.selectList(new QueryWrapper<IotProductServicePropEntity>().setEntity(iotProductServicePropEntity));
        Map serviceProperties = new HashMap();
        List<Map<String, Object>> propList = new ArrayList<>();
//        List<Map<String, Object>> parsingData = new ArrayList<>();
        for (IotProductServicePropEntity prop : iotProductServicePropList) {
            Map propMap = new HashMap();
            // prop的Id
            propMap.put("id", prop.getId());
            propMap.put("propertyName", prop.getPropertyName());
            propMap.put("dataType", prop.getDataType());
            propMap.put("required", prop.getRequired() == 0 ? false : true);
            propMap.put("min", prop.getMin());
            propMap.put("max", prop.getMax());
            propMap.put("step", prop.getStep());
            propMap.put("maxLength", prop.getMaxLength());
            propMap.put("method", prop.getMethod());
            propMap.put("unit", prop.getUnit());
            propMap.put("enumList", prop.getEnumList());
            propList.add(propMap);

            serviceProperties.put(prop.getPropertyName(),prop.getMin() );

//            HashMap<String, Object> parsedPro = getParsingData(prop);
//            parsingData.add(parsedPro);
        }
        Map data = new HashMap();
        data.put("serviceProperties", serviceProperties);
        data.put("propList", propList);
//        data.put("parsingData", parsingData);

        return OperResult.ok().put("data",data);
    }

//    /**
//     * 供前端解析使用（需统一格式）
//     * @param iotProductServicePropEntity
//     * @return
//     */
//    public HashMap<String, Object> getParsingData(IotProductServicePropEntity iotProductServicePropEntity) {
//        HashMap<String, Object> parsedPro = new HashMap<>();
//        parsedPro.put("min", iotProductServicePropEntity.getMin());
//        parsedPro.put("max", iotProductServicePropEntity.getMax());
//        return parsedPro;
//    }

    /**
     *
     *
     * csg/notify/event/gwTerminal/status/CSG300222/CSG/T20/KD-221T/mqtt/20200728test
     */
    public void online(IotDeviceEntity params) {
        String onOrOffline =Constant.ONLINE;
        String topic = Constant.APP_NAME +  Constant.UNDER_LINE
                + onlineTopic + Constant.UNDER_LINE
                + params.getManufacturerId() +  Constant.UNDER_LINE
                + params.getManufacturerName() + Constant.UNDER_LINE
                + params.getDeviceType() + Constant.UNDER_LINE
                + params.getModel() + Constant.UNDER_LINE
                + params.getProtocolType().toLowerCase() + Constant.UNDER_LINE
                + params.getNodeId();

        HashMap<String, Object> data = new HashMap<>();
        // TODO: 2022/5/6  token有用吗？
        data.put(Constant.MSG_TOKEN, "4d4a36a4-bfdf-11d3-9ab7-06e863fbd23d");
        String message ="";
        MqttMessage mqttMessage = new MqttMessage(message.getBytes());
        try {
            client.publish(topic,mqttMessage);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}
